package bluetooth;

import java.util.Vector;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

public class Client implements Runnable, DiscoveryListener
{
    private Connection connection;
    private DiscoveryAgent discoveryAgent; 
    private static final UUID ECHO_SERVER_UUID = new UUID("F0E0D0C0B0A000908070605040302010", false);
    Vector devices = new Vector(); 
    Vector records = new Vector();
    StreamConnection conn;
   
    int[]transIDs;
    private Thread processorThread;
    private boolean isClosed = false;
    private int discType;
    
    boolean isAttack_1,isObject_1,isEscape_1;
	boolean isSkill_1;
	int skill_1;
	boolean isAttack_2,isObject_2,isEscape_2;
	boolean isSkill_2;
	int skill_2;

    public Client(Connection connection)
    {
        this.connection = connection;
    }

    public void start()
    {
        processorThread = new Thread(this);
        processorThread.start();
    }

    public void sendMessage(boolean isAttack, boolean isObject,boolean isSkill, int skill, boolean isEscape) {
    		isAttack_1 = isAttack; 
    		isObject_1 = isObject;
    		isSkill_1 = isSkill;
    		skill_1 = skill;
    		isEscape_1 = isEscape;
    		Thread fetchThread = new Thread()
            {
                public void run()
                {
                    try
                    {
                    	
                    	ServiceRecord sr = (ServiceRecord)records.elementAt(0);
                        String url = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);               
                        conn = (StreamConnection)Connector.open(url);                 
                        DataOutputStream dos = conn.openDataOutputStream();
                        
                        dos.writeBoolean(isAttack_1);
                        dos.writeBoolean(isObject_1);
                        dos.writeBoolean(isSkill_1);
                        dos.write(skill_1);
                        dos.writeBoolean(isEscape_1);
                        dos.flush();
                        dos.close();

                        DataInputStream dis = conn.openDataInputStream();
                        isAttack_2 = dis.readBoolean();
                        isObject_2 = dis.readBoolean();
                        isSkill_2 = dis.readBoolean();
                        skill_2 = dis.read();
                        isEscape_2 = dis.readBoolean();
                        dis.close();
                        connection.receiveMessage(isAttack_2, isObject_2,isSkill_2,skill_2,isEscape_2);
                    }
                    catch (Exception e)
                    {
                        System.out.println("Exception");
                        e.printStackTrace();
                    }
                }
            };
            fetchThread.start();
    	}


    public synchronized void run()
    {

        try
        {
            LocalDevice local = LocalDevice.getLocalDevice();
            discoveryAgent = local.getDiscoveryAgent();

        }
        catch (BluetoothStateException e)
        {
            System.err.println("Can't initialize bluetooth: " + e);
        }


        try
        {
            discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
        
        }
        catch (BluetoothStateException bse){}

        try
        {
            wait(); 
        }
        catch (InterruptedException e)
        {
            System.err.println("Unexpected interuption: " + e);
            return ;
        }

        if (isClosed)
        {
            return ;
        }


        UUID[]uuids = new UUID[1];
        uuids[0] = ECHO_SERVER_UUID;
        transIDs = new int[devices.size()];
        if(devices.size()!=0){
        for (int i = 0; i < devices.size(); i++)
        {
            RemoteDevice rd = (RemoteDevice)devices.elementAt(i);
            try
            {
              
                System.out.println("begin searchservices");
                transIDs[i] = discoveryAgent.searchServices(null, uuids, rd,
                    this);
            }
            catch (BluetoothStateException e)
            {
                continue;
            }

        } 
      }
        try
        {
          
            wait();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println("Client run end");
    }


    public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass
        deviceClass)
    {
        devices.addElement(remoteDevice);
        System.out.println("discovered a device ");
        System.out.println(remoteDevice.getBluetoothAddress());
    } 
    public void inquiryCompleted(int discType)
    {
        System.out.println("start inquiry completed");
        this.discType = discType;
        if (discType != INQUIRY_COMPLETED || devices.size() == 0)
        {
            connection.completeInitialization(false);
        }
        synchronized(this)
        {
            notify();
        }
    }

    public void serviceSearchCompleted(int transID, int respCode)
    {
        System.out.println("complete service Search");
        switch (respCode)
        {
            case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                break;
            case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                break;
            case DiscoveryListener.SERVICE_SEARCH_ERROR:
                break;
            case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                break;
            case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                break;
        }
        synchronized(this)
        {
            notify();
        }

    }

    public void servicesDiscovered(int transID, ServiceRecord[]serviceRecord)
    {      
        System.out.println("get server");
        for (int i = 0; i < serviceRecord.length; i++)
        {
            records.addElement(serviceRecord[i]);
        }
    } 


    void destroy()
    {
        synchronized(this)
        {
            isClosed = true;
            notify();          
        }
  
        try
        {
            processorThread.join();
        }
        catch (InterruptedException e){}
     
    }

}
